package com.yunbiao.ybbusstopplate.doublescreen;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.Surface;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.daimajia.androidanimations.library.Techniques;
import com.daimajia.androidanimations.library.YoYo;
import com.yunbiao.ybbusstopplate.R;
import com.yunbiao.ybbusstopplate.bean.SiteInfoBean;
import com.yunbiao.ybbusstopplate.serialport.SerialPortConfig;
import com.yunbiao.ybbusstopplate.ui.view.SubwayLooper;
import com.yunbiao.ybbusstopplate.ui.view.SubwayLooper2;
import com.yunbiao.ybbusstopplate.ui.view.subway.StationEffect;
import com.yunbiao.ybbusstopplate.ui.view.subway.StationMap;
import com.yunbiao.ybbusstopplate.ui.view.subway.StationMap2;
import com.yunbiao.ybbusstopplate.ui.view.subway.StationMap3;
import com.yunbiao.ybbusstopplate.utils.SpTool;
import com.yunbiao.ybbusstopplate.utils.eventbus.EventMessage;
import com.yunbiao.ybbusstopplate.utils.eventbus.EventTAG;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class BusStopPlateView {
    private final TextView tvRoad;
    private final TextView tvLineName;
    private final TextView tvSiteStart;
    private final TextView tvSiteStart1;
    private final TextView tvSiteEnd;
    private final TextView tvSiteEnd1;
    private final FrameLayout fl_linelist;
    private final View ll_site_start;
    private final View ll_site_end;
    private final TextView tv_site_start_time;
    private final TextView tv_site_end_time;

    private final Context context;
    private final View rootView;
    private final Display display;
    private final TextView tv_sitename;
    private final TextView tv_road;
    private final TextView tv_linenum;
    private final TextView tv_site_start;
    private final TextView tv_site_end;
    private final TextView tv_site_start1;
    private final TextView tv_site_end1;
    private final TextView tv_tip_site;
    private final TextView tv_tip_arrived;
    private final TextView tv_tip_next;
    private final TextView tv_tip2;
    private final View ll_tip;

    public BusStopPlateView(Context context, Display display) {
        this.context = context;
        this.rootView = LayoutInflater.from(context).inflate(R.layout.fragment_busstopplate2, null);
        this.display = display;

        tvRoad = rootView.findViewById(R.id.tv_road);
        tvLineName = rootView.findViewById(R.id.tv_linenum);
        tvSiteStart = rootView.findViewById(R.id.tv_site_start);
        tvSiteStart1 = rootView.findViewById(R.id.tv_site_start1);
        tvSiteEnd = rootView.findViewById(R.id.tv_site_end);
        tvSiteEnd1 = rootView.findViewById(R.id.tv_site_end);
        fl_linelist = rootView.findViewById(R.id.fl_linelist);
        ll_site_start = rootView.findViewById(R.id.ll_site_start);
        ll_site_end = rootView.findViewById(R.id.ll_site_end);
        tv_site_start_time = rootView.findViewById(R.id.tv_site_start_time);
        tv_site_end_time = rootView.findViewById(R.id.tv_site_end_time);
        tv_sitename = rootView.findViewById(R.id.tv_sitename);
        tv_road = rootView.findViewById(R.id.tv_road);
        tv_linenum = rootView.findViewById(R.id.tv_linenum);
        tv_site_start = rootView.findViewById(R.id.tv_site_start);
        tv_site_end = rootView.findViewById(R.id.tv_site_end);
        tv_site_start1 = rootView.findViewById(R.id.tv_site_start1);
        tv_site_end1 = rootView.findViewById(R.id.tv_site_end1);
        tv_tip_site = rootView.findViewById(R.id.tv_tip_site);
        tv_tip_arrived = rootView.findViewById(R.id.tv_tip_arrived);
        tv_tip_next = rootView.findViewById(R.id.tv_tip_next);
        tv_tip2 = rootView.findViewById(R.id.tv_tip2);
        ll_tip = rootView.findViewById(R.id.ll_tip);

        rootView.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() {
            @Override
            public void onViewAttachedToWindow(View v) {
                initData();
            }

            @Override
            public void onViewDetachedFromWindow(View v) {
                EventBus.getDefault().unregister(this);

                if (playon!=null && playon.isRunning()){
                    playon.stop();
                }
                if(playoff != null && playoff.isRunning()){
                    playoff.stop();
                }
                if(effect != null){
                    effect.threadstop();
                    if(fl_linelist != null){
                        fl_linelist.removeView(effect);
                    }
                    effect = null;
                }
            }
        });
    }

    public View getRootView() {
        return rootView;
    }

    private boolean isPORTRAIT = false;
    private void initData(){
        EventBus.getDefault().register(this);

        int rotation = display.getRotation();
        if (rotation  == Surface.ROTATION_0 || rotation == Surface.ROTATION_180) {
            isPORTRAIT=false;
        }else{
            isPORTRAIT=true;
        }

        initDataOnStart();
    }

    private static final String TAG = "BusStopPlateView";
    private String[] lineInfo;
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventMessage eventMessage){
        switch (eventMessage.getMsgTag()) {
            case EventTAG.EVENT_UPDATESITELIST:
                Log.e(TAG, "onEvent: 11111111111111111111111111");
                ArrayList<String> lineList = (ArrayList<String>) eventMessage.getMsgData();
                updateLineList(lineList);
                break;
            case EventTAG.EVENT_LINEINFO:
                Log.e(TAG, "onEvent: 22222222222222222222222222");
                String[] lineInfo = (String[]) eventMessage.getMsgData();
                this.lineInfo = lineInfo;
                updateLine(lineInfo);
                break;
            case EventTAG.EVENT_SITETIME:
                Log.e(TAG, "onEvent: 33333333333333333333333333333333");
                String[] timeInfo = (String[]) eventMessage.getMsgData();
                String s1 = timeInfo[0];
                String e1 = timeInfo[1];
                String s2 = timeInfo[2];
                String e2 = timeInfo[3];
                updateSiteTime2();
                break;
            case EventTAG.EVENT_SITETIP:
                Log.e(TAG, "onEvent: 444444444444444444444444444444");
                SiteInfoBean siteInfo = (SiteInfoBean) eventMessage.getMsgData();
                if(siteInfo != null){
                    showTip(siteInfo);
                }
                break;
            case EventTAG.event_config_update:
                break;
        }
    }

    private void initDataOnStart(){

        String line_name = SpTool.Companion.get_line_name();
        if(!TextUtils.isEmpty(line_name)){
            if(line_name.endsWith("路")){
                line_name = line_name.replace("路","");
                tvRoad.setVisibility(View.VISIBLE);
            } else {
                tvRoad.setVisibility(View.GONE);
            }
            if(line_name.equals("充电")){
                fl_linelist.setVisibility(View.GONE);
            }else{
                fl_linelist.setVisibility(View.VISIBLE);
            }
            tvLineName.setText(line_name);
        }

        String site_start = SpTool.Companion.get_site_start();
        if(!TextUtils.isEmpty(site_start)){
            tvSiteStart.setText(site_start);
            tvSiteStart1.setText(site_start);
        }

        String site_end = SpTool.Companion.get_site_end();
        if(!TextUtils.isEmpty(site_end)){
            tvSiteEnd.setText(site_start);
            tvSiteEnd1.setText(site_start);
        }

        updateSiteTime2();

        String site_list = SpTool.Companion.get_site_list();
        if(!TextUtils.isEmpty(site_list)){
            String[] sites = site_list.split(",");
            if(sites.length > 0){
                tv_sitename.setText(sites[0]);

                list = new ArrayList<>(Arrays.asList(sites));
                fl_linelist.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        updateLineListUI(list);
                        updateSplashDot();
                        fl_linelist.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                    }
                });
            }
        }
    }

    private StationMap stationMap;
    private SubwayLooper loopView;
    private void updateLineListUI(List<String> list){
        if(stationMap != null){
            fl_linelist.removeView(stationMap);
            stationMap = null;
        }
        if(loopView != null){
            loopView.desty();
            fl_linelist.removeAllViews();
            loopView = null;
        }
        int configShowLineType = SpTool.Companion.getConfigShowLineType();
        if(configShowLineType == 1){
            String[] ss = new String[list.size()];
            String[] array = new String[list.size()];
            for (int i = 0; i < array.length; i++) {
                array[i] = list.get(i);
            }
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            int limitStationNum = 23;
            boolean configShowAdvert = SpTool.Companion.getConfigShowAdvert();
            if(!configShowAdvert){
                limitStationNum = 47;
            }
            if(isPORTRAIT){
                StationMap3.STATIONMAP_MAXFONTSIZE = Integer.parseInt(fl_linelist.getTag().toString());
                loopView = new SubwayLooper2(context,fl_linelist,list.size());
                loopView.setDatas(list);
            } else {
                StationMap.STATIONMAP_MAXFONTSIZE = Integer.parseInt(fl_linelist.getTag().toString());
                stationMap = new StationMap(context,array,limitStationNum);
                stationMap.setWidth_Height(fl_linelist.getWidth(),fl_linelist.getHeight());
                stationMap.SetStationNum(array.length);
                fl_linelist.addView(stationMap,params);
            }
        } else {
            fl_linelist.removeAllViews();
            boolean configShowAdvert = SpTool.Companion.getConfigShowAdvert();
            int count = 50;
            if(configShowAdvert){
                count = 30;
            }
            if(isPORTRAIT){
                StationMap3.STATIONMAP_MAXFONTSIZE = Integer.parseInt(fl_linelist.getTag().toString());
                loopView = new SubwayLooper2(context,fl_linelist,count);
            } else {
                StationMap2.STATIONMAP_MAXFONTSIZE = Integer.parseInt(fl_linelist.getTag().toString());
                loopView = new SubwayLooper(context,fl_linelist,count);
            }

            loopView.setDatas(list);
        }
    }

    private StationEffect effect;
    private void updateSplashDot(){
        if(effect != null){
            effect.threadstop();
            fl_linelist.removeView(effect);
            effect = null;
        }
        int configShowLineType = SpTool.Companion.getConfigShowLineType();
        if(configShowLineType == 1){
            effect = new StationEffect(context);
            fl_linelist.addView(effect);
        }
    }

    private ArrayList<String> list;
    private void updateLineList(ArrayList<String> list){
        if(list == null || list.isEmpty()){
            return;
        }
        this.list = list;
        tv_sitename.setText(list.get(0));
        updateLineListUI(list);
        updateSplashDot();
    }

    private void updateSiteTime2(){
        //updateSiteTime2-----------------------------
        ll_site_start.setVisibility(View.GONE);
        ll_site_end.setVisibility(View.GONE);
        boolean configShowLineTime = SpTool.Companion.getConfigShowLineTime();
        if(configShowLineTime){
            List<String> siteTime = SpTool.Companion.getSiteTime();
            if(siteTime != null && siteTime.size() > 0){
                String s1 = siteTime.get(0);
                String e1 = siteTime.get(0);
                String se1 = "";
                if(!TextUtils.isEmpty(s1)){
                    se1 += "首班" + s1;
                }
                if(!TextUtils.isEmpty(e1)){
                    se1 += "  末班" + e1;
                }
                tv_site_start_time.setText(se1);
                ll_site_start.setVisibility(View.VISIBLE);

                String s2 = siteTime.get(2);
                String e2 = siteTime.get(3);
                String se2 = "";
                if(!TextUtils.isEmpty(s2)){
                    se2 += "首班" + s2;
                }
                if(!TextUtils.isEmpty(e2)){
                    se2 += "  末班" + e2;
                }
                tv_site_end_time.setText(se2);
                ll_site_end.setVisibility(View.VISIBLE);
            }
        }
        //updateSiteTime2-----------------------------
    }


    private void updateLine(String[] lineInfo){
        arriveFirst = true;

        String lineName = lineInfo[0];
        if(lineName.endsWith("路")){
            lineName = lineName.replace("路","");
            tv_road.setVisibility(View.VISIBLE);
        } else {
            tv_road.setVisibility(View.GONE);
        }
        if(lineName.equals("充电")){
            fl_linelist.setVisibility(View.GONE);
        }else{
            fl_linelist.setVisibility(View.VISIBLE);

        }
        tv_linenum.setText(lineName);
        tv_site_start.setText(lineInfo[1]);
        tv_site_end.setText(lineInfo[2]);
        tv_site_start1.setText(lineInfo[1]);
        tv_site_end1.setText(lineInfo[2]);

        if(SerialPortConfig.Companion.getPORT_TYPE() == SerialPortConfig.TYPE_TK){
            lineName = SpTool.Companion.get_line_name();
            List<String> siteTime = SpTool.Companion.getSiteTime();
            if((lineInfo[0] + "路").equals(lineName) && siteTime != null){
                String startSiteLocal = SpTool.Companion.get_site_start();
                String startName = lineInfo[1];
                if(!startName.equals(startSiteLocal)){
                    String s1 = siteTime.get(0);
                    String e1 = siteTime.get(1);
                    String s2 = siteTime.get(2);
                    String e2 = siteTime.get(3);
                }
                updateSiteTime2();
            } else {
                updateSiteTime2();
            }
        } else {
            updateSiteTime2();
        }
    }

    private int getPosition(String name){
        int indexOf = list.indexOf(name);
        if(indexOf == -1){
            indexOf = 0;
        }
        return indexOf;
    }

    private YoYo.YoYoString playoff = null;
    private YoYo.YoYoString playon = null;
    private boolean arriveFirst=false;
    private void showTip(SiteInfoBean siteInfo){
        Log.e(TAG, "showTip: 55555555555555555555555555");
        int index = siteInfo.getIndex();
        String siteName = "";
        if(index < 0){
            siteName = siteInfo.getSiteName();
            Log.e(TAG, "showTip: ****************************");
        } else {
            if(index >= list.size()){
                index = list.size() - 1;
            }
            siteName = list.get(index);
            Log.e(TAG, "showTip: ++++++++++++++++++++++++++++");
        }
        Log.e(TAG, "showTip: 999999999999999999999999999999");
        if(TextUtils.isEmpty(siteName)){
            return;
        }
        Log.e(TAG, "showTip: 6666666666666666666666666666");
        tv_tip_site.setText(siteName);
        if(siteInfo.getStutas() == 1){
            Log.e(TAG, "showTip: 888888888888888888888888888888888");
            int configShowLineType = SpTool.Companion.getConfigShowLineType();
            int position = 0;
            if(SerialPortConfig.Companion.getPORT_TYPE() == SerialPortConfig.TYPE_HX){
                position = siteInfo.getIndex();
            } else {
                position = getPosition(siteName);
            }

            if(position == 0 || arriveFirst){
                arriveFirst = false;

                if(isPORTRAIT){
                    loopView.setCurrenPosition(0);
                } else {
                    if(configShowLineType == 1){
                        stationMap.SetStationCur(0);
                    } else {
                        loopView.setCurrenPosition(0);
                    }
                }
            }
            tv_sitename.setText(siteInfo.getSiteName());
            tv_tip_arrived.setVisibility(View.VISIBLE);
            tv_tip_next.setVisibility(View.GONE);
            tv_tip2.setText("开门请当心，下车时注意安全！");

            if(ll_tip.getVisibility() != View.VISIBLE){
                showon();
            }
            if(isPORTRAIT){
                loopView.setCurrenPosition(position);
            } else {
                if(configShowLineType == 1){
                    stationMap.SetStationCur(position);
                } else {
                    loopView.setCurrenPosition(position);
                }
            }
            if(siteInfo.getSiteName().isEmpty() && siteInfo.getIndex() >= list.size() - 1){
                showoff(10);
            } else if(siteInfo.getSiteName().equals(list.get(list.size() - 1))){
                showoff(10);
            }
        } else {
            Log.e(TAG, "showTip: 77777777777777777777777777777");
            tv_tip_arrived.setVisibility(View.GONE);
            tv_tip_next.setVisibility(View.VISIBLE);
            tv_tip2.setText("车辆起步，请坐稳扶好！");
            int showTime = siteInfo.getShowTime();
            if(showTime < 10){
                showTime = 10;
            }
            showoff(showTime);
        }
    }

    private void stopOff(){
        if(playoff != null){
            playoff.stop();
        }
    }

    private void showon(){
        stopOff();
        playon= YoYo.with(Techniques.SlideInRight)
                .duration(1000)
                .onStart(animator -> ll_tip.setVisibility(View.VISIBLE))
                .onEnd(animator -> ll_tip.setVisibility(View.VISIBLE))
                .playOn(ll_tip);
    }

    private void showoff(int showTime){
        stopOff();
        playoff = YoYo.with(Techniques.SlideOutRight)
                .duration(1000)
                .delay(showTime * 1000L)
                .onStart(animator -> ll_tip.setVisibility(View.VISIBLE))
                .onEnd(animator -> ll_tip.setVisibility(View.INVISIBLE))
                .playOn(ll_tip);
    }


}
